package repo

import (
	"time"

	"github.com/jinzhu/gorm"

	"github.com/pingcap-incubator/tidb-dashboard/pkg/model"
)

func InsertUserRole(db *gorm.DB, userID string, roleID uint) error {
	t := time.Now()
	if err :=
		db.Table(UserRoleTable).
			Set("gorm:insert_modifier", "IGNORE").
			Create(&model.UserRole{RoleID: roleID, UserID: userID, CreateTime: &t}).
			Error; err != nil {
		return ErrExecute.Wrap(err, "insert user role error")
	}
	return nil
}

func GetUserRole(db *gorm.DB, userID string) ([]model.GetUserRole, error) {
	var result []model.GetUserRole

	err := db.Raw("SELECT user_role.id,role.role,role.description,role.id as role_id FROM tidb_dashboard.role "+
		"left join tidb_dashboard.user_role "+
		"on user_role.role_id = role.id "+
		"where role.status=1 and user_role.user_id= ?", userID).
		Scan(&result).Error

	if err != nil {
		return nil, err
	}

	return result, nil
}

func DeleteUserRoles(db *gorm.DB, userID string, roleIDs []uint) error {
	if err :=
		db.Table(UserRoleTable).
			Where("user_id = ?", userID).
			Where("role_id in (?)", roleIDs).
			Delete(model.UserRole{}).Error; err != nil {
		return ErrExecute.Wrap(err, "delete user role error")
	}
	return nil
}

func DeleteUserRolesByUserID(db *gorm.DB, userID string) error {
	if err :=
		db.Table(UserRoleTable).
			Where("user_id = ?", userID).
			Delete(model.UserRole{}).Error; err != nil {
		return ErrExecute.Wrap(err, "delete user role error")
	}
	return nil
}
